<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="入库单" prop="purchaseOrderId">
        <el-input
            v-model="queryParams.purchaseOrderNo"
            placeholder="请输入入库单"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable  style="width: 180px">
          <el-option v-for="dict in purchase_return_status" :key="dict.value" :label="dict.label" :value="dict.value"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['purchase:return:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['purchase:return:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="returnList">
<!--      <el-table-column label="退货单号" align="center" prop="purchaseReturnNo" width="210"/>-->
      <el-table-column label="退货单号" align="center" prop="purchaseReturnNo" width="210">
        <template #default="scope">
          <span @click="handleShowDetails(scope.row)" style="color: #1c84c6">{{scope.row.purchaseReturnNo}}</span>
        </template>
      </el-table-column>
      <el-table-column label="订单单号" align="center" prop="purchaseOrderNo" width="210"/>
      <el-table-column label="供应商" align="center" prop="suppliersName" />
      <el-table-column label="联系电话" align="center" prop="supplierTel" />
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="purchase_return_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="210">
        <template #default="scope">
          <!-- 根据 status 值显示不同按钮 -->
          <template v-if="scope.row.status === 0">
            <el-button link type="primary" icon="Edit" v-hasPermi="['purchase:return:edit']" @click="handleUpdate(scope.row)">修改</el-button>
            <el-button link type="primary" icon="Delete" v-hasPermi="['purchase:return:remove']" @click="handleDelete(scope.row)">删除</el-button>
            <el-button link type="primary" icon="link" v-hasPermi="['purchase:return:edit']" @click="handleSubmit(scope.row)">提交</el-button>
          </template>
          <template v-else-if="scope.row.status === 1">
            <el-button link type="primary" icon="CircleCheck" @click="handleApprove(scope.row)" v-hasPermi="['purchase:return:edit']">申请通过</el-button>
            <el-button link type="primary" icon="CircleClose" @click="handleReject(scope.row)" v-hasPermi="['purchase:return:edit']">审核驳回</el-button>
          </template>
          <template v-else-if="scope.row.status === 2">
            <el-button link type="primary" icon="CircleCheck" @click="handleStatus(scope.row)" v-hasPermi="['purchase:return:edit']">已退货</el-button>
          </template>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList"/>

    <!-- 添加或修改采购退货对话框 -->
    <el-dialog :title="title" v-model="open"  append-to-body style="width: 70%;height: 80%">
      <el-form ref="returnRef" :model="form" :rules="rules" label-width="80px">
        <div style="display: flex;">
          <el-form-item label="退货单号">
            <el-input v-model="form.purchaseReturnNo" disabled style="width: 210px"/>
          </el-form-item>
          <el-form-item label="订单编号" prop="purchaseOrderId">
            <el-select v-model="form.purchaseOrderId" placeholder="请选择申请编号" style="width: 240px">
              <el-option v-for="option in selectOrderOptions" :key="option.value" :label="option.label" :value="option.value"/>
            </el-select>
          </el-form-item>
        </div>
        <div>
          <h2>采购退货清单</h2>
          <el-col :span="1.5" class="mb8">
            <el-button type="primary" plain icon="Plus" @click="handleAddMaterial">新增</el-button>
          </el-col>

          <el-table  style="height: 300px; overflow: auto;" :data="purchaseReturnGoods">
            <el-table-column label="物料名称" align="center" prop="materialName" >
              <template #default="scope">
                <el-select
                    v-model="scope.row.materialId"
                    placeholder="Select"
                    size="large"
                    style="width: 240px"
                >
                  <el-option v-for="option in selectMaterialOptions" :key="option.value" :label="option.label" :value="option.value"/>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="数量" align="center" prop="purchaseReturnNumber" >
              <template #default="scope">
                <el-input-number v-model="scope.row.purchaseReturnNumber"></el-input-number>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="300" v-if="!data.isAdding">
              <template #default="scope" >
                <el-button link type="primary" icon="Delete" @click="handleDeleteMaterial(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!--  采购退货详情页  -->
    <el-dialog :title="title" v-model="openA" style="width: 70%; height: 80%" append-to-body>
      <el-form ref="orderRef" :model="form" :rules="rules" >
        <div style="display: flex;">
          <el-form-item label="退货单号" style="margin-right: 50px" >
            <el-input v-model="form.purchaseReturnNo" disabled style="width: 210px" />
          </el-form-item>
          <el-form-item label="订单编号" >
            <el-input v-model="form.purchaseOrderNo" disabled style="width: 210px" />
          </el-form-item>
        </div>
        <div>
          <h2>采购订单清单</h2>
          <el-table  style="height: 320px; overflow: auto;" :data="purchaseReturnGoods">
            <el-table-column label="物料名称" align="center" prop="materialName" />
            <el-table-column label="数量" align="center" prop="purchaseReturnNumber" />
            <el-table-column label="单位" align="center" prop="unitId">
              <template #default="scope">
                <dict-tag :options="unit_type" :value="scope.row.unitId" />
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup name="Return">
import { listReturn, getReturn, delReturn, addReturn, updateReturn,getCGTH } from "@/api/purchase/return";
import {listOrder} from "../../../api/purchase/order.js";
import {listMaterials} from "../../../api/base/materials.js";
import {ElMessageBox} from "element-plus";
import {changeStatus} from "../../../api/purchase/return.js";

const { proxy } = getCurrentInstance();
const { purchase_return_status,unit_type } = proxy.useDict('purchase_return_status','unit_type');

const returnList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const openA = ref(false);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {
    purchaseReturnGoods: []
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    purchaseOrderId: null,
    purchaseReturnNo: null,
    status: null,
  },
  rules: {
    purchaseOrderId: [
      { required: true, message: "采购订单不能为空", trigger: "blur" }
    ],
    status: [
      { required: true, message: "状态0未审核;1审核通过:2审核驳回不能为空", trigger: "change" }
    ],
    createTime: [
      { required: true, message: "创建时间不能为空", trigger: "blur" }
    ],
    createBy: [
      { required: true, message: "创建人不能为空", trigger: "blur" }
    ],
  }
});
const purchaseReturnGoods = ref([])

const { queryParams, form, rules } = toRefs(data);

/** 查询采购退货列表 */
function getList() {
  loading.value = true;
  listReturn(queryParams.value).then(response => {
    returnList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    purchaseOrderId: null,
    status: null,
    createTime: null,
    createBy: null,
    updateTime: null,
    updateBy: null
  };
  proxy.resetForm("returnRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}
// 新增采购退货清单
function handleAddMaterial(){
  let obj = {
    materialId: '',
    purchaseReturnNumber: ''
  }
  purchaseReturnGoods.value.push(obj);
}

const orderList = ref([]);
const materialsList = ref([]);

// 获取采购申请单列表
const getOrderList = async () => {
  const response = await listOrder({ status: 4 });
  orderList.value = response.rows;
  // console.log(orderList.value)
};
/** 查询物料管理列表 */
const getMaterialList = async () =>  {
  const response = await listMaterials();
  materialsList.value = response.rows
  // console.log(materialsList.value)
}
// 在页面加载时获取用户列表、物料列表
onMounted(() => {
  getOrderList();
  getMaterialList();
});

const selectOrderOptions = computed(() => {
  return orderList.value.map(purchaseOrder => ({ label: purchaseOrder.purchaseOrderNo, value: purchaseOrder.id }));
});
const selectMaterialOptions = computed(() => {
  return materialsList.value.map(material => ({ label: material.materialName, value: material.id}));
});

/** 新增按钮操作 */
function handleAdd() {
  reset();
  purchaseReturnGoods.value = []
  form.value.purchaseReturnGoods = purchaseReturnGoods;
  getCGTH().then(response => {
    form.value.purchaseReturnNo= response.msg
  })
  open.value = true;
  title.value = "添加采购退货";
}
// 提交按钮操作函数
function handleSubmit(row) {
  ElMessageBox.confirm('是否确认提交？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 提交后状态变为 1
    row.status=1
    changeStatus(row.id,row.status).then(() => {
      getList();
    });
  }).catch(() => {});
}

// 申请通过按钮操作函数
function handleApprove(row) {
  ElMessageBox.confirm('是否确认申请通过？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 申请通过后状态变为 2
    row.status=2
    changeStatus(row.id, row.status).then(() => {
      getList();
    });
  }).catch(() => {});
}

// 申请通过按钮操作函数
function handleStatus(row) {
  ElMessageBox.confirm('是否确认已退货？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 申请通过后状态变为 2
    row.status=3
    changeStatus(row.id, row.status).then(() => {
      getList();
    });
  }).catch(() => {});
}
// 审核驳回按钮操作函数
function handleReject(row) {
  ElMessageBox.confirm('是否确认审核驳回？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 审核驳回后状态变为 3
    row.status = 3
    changeStatus(row.id, row.status).then(() => {
      getList();
    });
  }).catch(() => {});
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getReturn(_id).then(response => {
    form.value = response.data;
    purchaseReturnGoods.value = response.data.purchaseReturnGoods
    open.value = true;
    title.value = "修改采购退货";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["returnRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateReturn(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addReturn(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除采购退货编号为"' + _ids + '"的数据项？').then(function() {
    return delReturn(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/return/export', {
    ...queryParams.value
  }, `return_${new Date().getTime()}.xlsx`)
}

// 显示详情页
function handleShowDetails(row) {
  form.value = {...row };
  // 将采购申请列表数据赋值给详情页的列表数据
  purchaseReturnGoods.value = row.purchaseReturnGoods || [];
  openA.value = true;
  title.value = "采购申请详情";
}

getList();
</script>
